//获取邮件信息
package mymail;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
public class DoReceive {
    
    private MimeMessage message = null;
    private StringBuffer mailbody = new StringBuffer();
    private String dateformate = "yy-MM-dd HH:mm";
    
    public DoReceive(MimeMessage message){
        this.message = message;
        }
    public void setMsg(MimeMessage message) {
        this.message = message;
    }
    
    /**
     * 获取发送邮件者信息
     * 
     */
    public String getFrom() throws MessagingException{
        InternetAddress[] address = (InternetAddress[]) message.getFrom();
        String from = address[0].getAddress();
        if(from == null){
            from = "";
        }
        /*String personal = address[0].getPersonal();
        if(personal == null){
            personal = "";
        }*/
        return from;
    }
    
    /**
     * 获取邮件收件人，抄送，密送的地址和信息。
     * @param type
     * 
     */
    public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException{
        String mailaddr = "";
        String addrType = type.toUpperCase();
        InternetAddress[] address = null;
        
        if(addrType.equals("TO")||addrType.equals("CC")||addrType.equals("BCC")){
            if(addrType.equals("TO")){
                address = (InternetAddress[]) message.getRecipients(Message.RecipientType.TO);
            }
            if(addrType.equals("CC")){
                address = (InternetAddress[]) message.getRecipients(Message.RecipientType.CC);
            }
            if(addrType.equals("BCC")){
                address = (InternetAddress[]) message.getRecipients(Message.RecipientType.BCC);
            }
            
            if(address != null){
                for(int i=0;i<address.length;i++){
                    String mail = address[i].getAddress();
                    if(mail == null){
                        mail = "";
                    }else{
                        mail = MimeUtility.decodeText(mail);
                    }
                    String personal = address[i].getPersonal();
                    if(personal == null){
                        personal = "";
                    }else{
                        personal = MimeUtility.decodeText(personal);
                    }
                    String compositeto = personal +"<"+mail+">";
                    mailaddr += ","+compositeto; 
                }
                mailaddr = mailaddr.substring(1);
            }
        }else{
            throw new RuntimeException("Error email Type!");
        }
        return mailaddr;
    }
    
    /**
     * 获取邮件主题
     * 
     */
    public String getSubject() throws UnsupportedEncodingException, MessagingException{
        String subject = "";
        subject = MimeUtility.decodeText(message.getSubject());
        if(subject == null){
            subject = "";
        }
        return subject;
    }
    
    /**
     * 获取邮件发送日期
     * 
     */
    public String getSendDate() throws MessagingException{
        Date sendDate = message.getSentDate();
        SimpleDateFormat smd = new SimpleDateFormat(dateformate);
        return smd.format(sendDate);
    }
    
    /**
     * 获取邮件正文内容
     * @return
     */
    public String getMailbody(){
        
        return mailbody.toString();
    }

    public void getMailContent(Part part) throws MessagingException, IOException{
        
        String contentType = part.getContentType();
        int nameindex = contentType.indexOf("name");
        boolean conname = false;
        if(nameindex != -1){
            conname = true;
        }
        System.out.println("CONTENTTYPE:"+contentType);
        if (part.isMimeType("text/html")&& !conname) {
            mailbody.append((String)part.getContent());
        }else if(part.isMimeType("text/plain")&& !conname){
            mailbody.append((String)part.getContent());
        }else if (part.isMimeType("multipart/*")) {
        	Multipart multipart = (Multipart) part.getContent();
        	int count = multipart.getCount();
        	boolean hasHtml = checkHasHtml(multipart);//这里校验是否有text/html内容
        	for(int index = 0 ; index < count ; index++ ){
        		Part temp = multipart.getBodyPart(index);
        		if(temp.isMimeType("text/plain")&&hasHtml){
        			//有html格式的则不显示无格式文档的内容
        		}else{
        			getMailContent(temp);
        		}
        	}
        }else if (part.isMimeType("message/rfc822")) {
        	getMailContent((Part) part.getContent()); 
        } 
    }
    
    public boolean checkHasHtml(Multipart part) throws MessagingException, IOException{
    	boolean hasHtml = false;
    	int count = part.getCount();
    	for(int i = 0 ; i < count ; i++ ){
    		Part bodyPart = part.getBodyPart(i);
    		if (bodyPart.isMimeType("text/html")) {
    			hasHtml = true;
    			break;
    		}
    	}
    	return hasHtml;
    }

    public boolean getReplySign() throws MessagingException{
        boolean replySign = false;
        String needreply[] = message.getHeader("Disposition-Notification-TO");
        if(needreply != null){
            replySign = true;
        }
        return replySign;
    }

    public String getMessageId() throws MessagingException{
        return message.getMessageID();
    }
/**
 * 检查是否是已读邮件
 * @return
 * @throws MessagingException
 */
    public boolean isNew() throws MessagingException{
        boolean isnew = false;
        Flags flags = ((Message)message).getFlags();
        Flags.Flag[] flag = flags.getSystemFlags();
        System.out.println("flags's length:"+flag.length);
        for(int i=0;i<flag.length;i++){
            if(flag[i]==Flags.Flag.SEEN){
                isnew = true;
                break;
            }
        }
        
        return isnew;
    }
    
    public void setDateformate(String dateformate) {
        this.dateformate = dateformate;
    }

}